import { DEFAULT_WALLPAPER } from '@/setting';
import { routerRedux } from 'dva/router';
import axios from 'axios';
import { message } from 'antd';
import { getWallPaper, setWallPaper } from '@/utils/wallpaper';
import { getAuthority, setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { fakeAccountLogin } from '@/services/login';
import { delay } from 'redux-saga';
import key from 'keymaster';
import { formatMessage } from 'umi/locale';

export default {
  namespace: 'login',
  state: {
    status: undefined,
    default_wallpaper: getWallPaper(),
    wallpapers: [
      { id: '01', value: '黄昏' },
      { id: '02', value: '旧金山大桥' },
      { id: '03', value: '海浪' },
      { id: '04', value: '早晨的树林' },
      { id: '05', value: '雪山' },
    ],
  },
  effects: {
    *login ({ payload }, { put, call }) {
      const response = yield call(fakeAccountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: !!response.code
        },
      });
      if (response.code === 1) {
        message.loading(formatMessage({ id: 'signin.success' }), 1.5)
        setAuthority('admin');
        yield call(delay, 2000);
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        yield put(routerRedux.replace(redirect || '/dashboard'));
      } else {
        message.error(response.message);
      }
    },
    *logout (_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false
        },
      });
      setAuthority();
      yield put(
        routerRedux.push({
          pathname: '/login',
          search: stringify({
            redirect: window.location.href,
          }),
        })
      );
    },
    *changeWallPaper ({ payload }, { put }) {
      const key = payload;
      yield put({
        type: 'change',
        key
      })
    }

  },
  reducers: {
    change (state, action) {
      const default_wallpaper = action.key;
      setWallPaper(default_wallpaper);
      return {
        ...state,
        default_wallpaper,
      };
    },
    changeLoginStatus (state, { payload }) {
      setAuthority();
      return {
        ...state,
        status: payload.status,
      };
    },
  },
  subscriptions: {
    setup ({ history }) {

    },
    keyboardWatcher ({ dispatch }) {
      key('enter, ctrl+enter', () => { dispatch({ type: 'login/login' }) });
    },
  },
};
